package com.doctcloud.hisinfo.medrec.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doctcloud.common.core.utils.DateUtils;
import com.doctcloud.hisinfo.histable.domain.medrec.PatVisitDo;
import com.doctcloud.hisinfo.medrec.mapper.PatVisitDoMapper;
import com.doctcloud.hisinfo.medrec.service.IPatVisitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.doctcloud.common.core.utils.DateUtils.format;

@Service
@Slf4j
public class PatVisitService extends ServiceImpl<PatVisitDoMapper, PatVisitDo> implements IPatVisitService {
    /**
     * 查询在指定时间区间内有入院或出院变动的患者就诊记录
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 符合条件的就诊记录列表
     */
    @Override
    public List<PatVisitDo> rangeChangeList(Date startDate, Date endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mi:ss");
        // 1. 参数校验
        if (startDate == null || endDate == null) {
            log.error("查询参数 startDate 或 endDate 不能为空");
            // 返回空列表，避免返回null导致调用方空指针异常
            return Collections.emptyList();
        }

        if (startDate.after(endDate)) {
            log.warn("查询参数 startDate [{}] 晚于 endDate [{}]，返回空列表",
                    DateUtils.format(startDate, true),
                    DateUtils.format(endDate, true));
            return Collections.emptyList();
        }

        // 2. 构建查询条件
        LambdaQueryWrapper<PatVisitDo> query = Wrappers.lambdaQuery();

        query.and(wrapper -> wrapper
                .ge(PatVisitDo::getAdmissionDateTime, startDate)
                .le(PatVisitDo::getAdmissionDateTime, endDate)
        ).or(wrapper -> wrapper
                .ge(PatVisitDo::getDischargeDateTime, startDate)
                .le(PatVisitDo::getDischargeDateTime, endDate)
        );

        return baseMapper.selectList(query);
    }

    @Override
    public List<PatVisitDo> adminAfter(Date inputDate) {
        LambdaQueryWrapper<PatVisitDo> query = Wrappers.lambdaQuery();
        query.ge(PatVisitDo::getAdmissionDateTime,inputDate);
        return baseMapper.selectList(query);
    }

    @Override
    public List<PatVisitDo> dischargeAfter(Date inputDate) {
        LambdaQueryWrapper<PatVisitDo> query = Wrappers.lambdaQuery();
        query.ge(PatVisitDo::getDischargeDateTime, inputDate);
        return baseMapper.selectList(query);
    }
}
